package me.cafeitu.demo.activiti.self;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;


import junit.framework.Assert;

public class SayHelloToLeaveTest2 {
	
	@Test
	public void testStartProcess() throws Exception{
		ProcessEngine processEngine = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration().buildProcessEngine();
		RepositoryService repositoryService = processEngine.getRepositoryService();
		repositoryService.createDeployment().addClasspathResource("jbpm/SayHelloToLeave.bpmn20.xml").deploy();
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
		Assert.assertEquals("SayHelloToLeave", processDefinition.getKey());
		
		RuntimeService runtimeService = processEngine.getRuntimeService();
		Map<String, Object> variables = new HashMap<String,Object>();
		variables.put("applyUser", "employee1");
		variables.put("days", 3);
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("SayHelloToLeave",variables);
		Assert.assertNotNull(processInstance);
		System.out.println("pid="+processInstance.getId() +" , pdid="+processInstance.getProcessDefinitionId());
		
		TaskService taskService = processEngine.getTaskService();
		Task taskOfDeptLeader = taskService.createTaskQuery().taskCandidateGroup("deptLeader").singleResult();
		Assert.assertNotNull(taskOfDeptLeader);
		Assert.assertEquals("领导审批",taskOfDeptLeader.getName());
		
		taskService.claim(taskOfDeptLeader.getId(), "leaderUser");
		variables = new HashMap<String,Object>();
		variables.put("approved", true);
		taskService.complete(taskOfDeptLeader.getId(),variables);
		taskOfDeptLeader = taskService.createTaskQuery().taskCandidateGroup("deptLeader").singleResult();
		Assert.assertNull(taskOfDeptLeader);
		
		HistoryService historyService = processEngine.getHistoryService();
		long count = historyService.createHistoricProcessInstanceQuery().finished().count();
		Assert.assertEquals(1, count);
	}
}
